import { useSelector } from 'react-redux';
import { Navigate, useLocation } from 'react-router-dom';
import { whiteList } from './router';
import { State } from './store';

export default function Permission({ children }: { children: JSX.Element }) {
  const location = useLocation();
  const token = useSelector<State, string>((state) => state.auth.token);
  if (whiteList.includes(location.pathname) || token) {
    return children;
  }
  return (
    <Navigate
      to={`/login?redirect=${location.pathname.slice(1)}`}
      state={{ from: location }}
      replace
    />
  );
}
